package com.shpng.cheapenglish.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shpng.cheapenglish.entity.SUser;
import com.shpng.cheapenglish.entity.SUserUnit;
import com.shpng.cheapenglish.entity.SWord;
import com.shpng.cheapenglish.manager.UserManager;
import com.shpng.cheapenglish.manager.WordManager;
import com.shpng.cheapenglish.util.StringUtils;

//目前翻译使用google api
public class WordReciteAction {

	private String unit;

	public String execute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		WordManager wordManager = WordManager.getInstance();
		UserManager userManager = UserManager.getInstance();

		SUser user = userManager.getUser((String) req.getSession()
				.getAttribute("email"));
		if (req.getSession().getAttribute("words") != null) {
			req.getSession().removeAttribute("words");
		}
		if (StringUtils.isEmpty(unit)) {
			resp.getWriter().print("{error:'未选择单元'}");
			return null;
		}
		SUserUnit suu = wordManager.getUserUnit(unit.trim(), user);
		List<Long> wordIds = wordManager.getWordIdsByDegreeOrder(suu);
		req.getSession().setAttribute("wordIds", wordIds);
		List<SWord> reciteWords = new ArrayList<SWord>();
		Iterator<Long> iterator = wordIds.iterator();
		for (int i = 0; i < 20 && iterator.hasNext(); i++) {
			reciteWords.add(wordManager.getWord(iterator.next()));
			iterator.remove();
		}
		StringBuilder sb = new StringBuilder();
		sb.append("{\"words\":[");
		for (SWord word : reciteWords) {
			sb.append(word.toJsonString());
			sb.append(",");
		}
		if (sb.charAt(sb.length() - 1) == ',')
			sb.deleteCharAt(sb.length() - 1);
		sb.append("]}");

		resp.setContentType("text/xml;charset=utf-8");
		resp.getWriter().print(sb.toString());
		return null;
	}

	public String getUnit() {
		return unit;
	}

	public void setUnit(String unit) {
		this.unit = unit;
	}

}
